import React, {useEffect, useState} from 'react';
import {
    Space,
    Switch,
    Table,
    Button,
    Modal,
    Form,
    Input,
    InputNumber,
    DatePicker,
    TreeSelect
} from 'antd';
import {
    PlusOutlined,
} from '@ant-design/icons';
import moment from 'moment';
import {IconMap} from "antd/es/result";

const { Item } = Form;
const { SHOW_PARENT } = TreeSelect;

const RoleTable = ({ roleData, setRoleData,menuData,setMenuData }) => {
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [isAddMode, setIsAddMode] = useState(false);
    const [selectedRecord, setSelectedRecord] = useState(null);
    const [dataSource, setDataSource] = useState(roleData);
    const [filteredData, setFilteredData] = useState(roleData);
    const [currentPage, setCurrentPage] = useState(1);
    const [pageSize, setPageSize] = useState(5);
    const [isMenuModalVisible, setIsMenuModalVisible] = useState(false);
    const [assignedMenus, setAssignedMenus] = useState([]);
    const [searchTerm, setSearchTerm] = useState('');

    const handleEdit = (record) => {
        setSelectedRecord(record);
        setIsAddMode(false);
        setIsModalVisible(true);
    };

    const handleDelete = (record) => {
        const updatedData = dataSource.filter(item => item.key !== record.key);
        setDataSource(updatedData);
        setFilteredData(updatedData);
        setRoleData(updatedData);
    };

    const handleAdd = () => {
        setSelectedRecord(null);
        setIsAddMode(true);
        setIsModalVisible(true);
    };

    const handleOk = () => {
        setIsModalVisible(false);
    };

    const handleCancel = () => {
        setIsModalVisible(false);
    };

    const onFinish = (values) => {
        const newKey = selectedRecord ? selectedRecord.key : `${dataSource.length + 1}`;
        const newRecord = {
            key: newKey,
            id: newKey,
            roleName: values.roleName,
            description: values.description,
            userCount: values.userCount,
            addTime: values.addTime.format('YYYY-MM-DD'),
            isEnabled: values.isEnabled,
        };

        if (isAddMode) {
            const updatedData = [...dataSource, newRecord];
            setDataSource(updatedData);
            setFilteredData(updatedData);
            setRoleData(updatedData);
        } else {
            const updatedData = dataSource.map(item =>
                item.key === newRecord.key ? newRecord : item
            );
            setDataSource(updatedData);
            setFilteredData(updatedData);
            setRoleData(updatedData);
        }

        setIsModalVisible(false);
    };

    const handleAssignMenu = (record) => {
        console.log('分配菜单');
        setSelectedRecord(record);
        setIsMenuModalVisible(true);
        setAssignedMenus(record.menuPermissions || []);
    };

    const handleMenuOk = () => {
        const updatedRoleData = roleData.map(role => {
            if (role.key === selectedRecord.key) {
                return { ...role, menuPermissions: assignedMenus };
            }
            return role;
        });
        setRoleData(updatedRoleData);
        setIsMenuModalVisible(false);
    };

    // 这里是默认的菜单数据
    const onChange = (newValue) => {
        setAssignedMenus(newValue);
        console.log('onChange ', newValue);
    };

    const handleMenuCancel = () => {
        setIsMenuModalVisible(false);
    };

    const columns = [
        {
            title: '编号',
            dataIndex: 'key',
            key: 'key',
        },
        {
            title: '角色名称',
            dataIndex: 'roleName',
            key: 'roleName',
        },
        {
            title: '描述',
            dataIndex: 'description',
            key: 'description',
        },
        {
            title: '用户数',
            dataIndex: 'userCount',
            key: 'userCount',
        },
        {
            title: '添加时间',
            dataIndex: 'addTime',
            key: 'addTime',
        },
        {
            title: '是否启用',
            dataIndex: 'isEnabled',
            key: 'isEnabled',
            render: (isEnabled, record) => (
                <Switch
                    checked={isEnabled}
                    onChange={(checked) => {
                        const updatedData = dataSource.map(item =>
                            item.key === record.key ? { ...item, isEnabled: checked } : item
                        );
                        setDataSource(updatedData);
                        setFilteredData(updatedData);
                        setRoleData(updatedData);
                    }}
                />
            ),
        },
        {
            title: '操作',
            key: 'actions',
            render: (text, record) => (
                <Space size="middle">
                    <Button type="primary" onClick={() => handleEdit(record)}>编辑</Button>
                    <Button type="danger" onClick={() => handleDelete(record)}>删除</Button>
                    <Button onClick={() => handleAssignMenu(record)}>分配菜单</Button>
                </Space>
            ),
        },
    ];

    const handleTableChange = (pagination) => {
        setCurrentPage(pagination.current);
        setPageSize(pagination.pageSize);
    };

    const handleSearch = (e) => {
        const { value } = e.target;
        setSearchTerm(value);
        const filteredData = dataSource.filter(item =>
            item.roleName.toLowerCase().includes(value.toLowerCase()) ||
            item.description.toLowerCase().includes(value.toLowerCase())
        );
        setFilteredData(filteredData);
    };

    return (
        <>
            <div className="addButtonContainer">
                <PlusOutlined className="addIcon" />
                <span className="addText">角色管理</span>
                <Input.Search
                    placeholder="搜索角色名称或描述"
                    value={searchTerm}
                    onChange={handleSearch}
                    className="searchInput"
                    style={{ marginBottom: 16 }}
                />
                <Button type="primary" className="addButton" onClick={handleAdd}>
                    新增
                </Button>
            </div>

            <Table
                columns={columns}
                dataSource={filteredData}
                pagination={{
                    current: currentPage,
                    pageSize: pageSize,
                    total: filteredData.length,
                    showSizeChanger: true,
                }}
                onChange={handleTableChange}
            />
            <Modal
                title={isAddMode ? "新增角色" : "编辑角色"}
                open={isModalVisible}
                onOk={handleOk}
                onCancel={handleCancel}
                footer={null}
            >
                <Form onFinish={onFinish} initialValues={selectedRecord ? {
                    roleName: selectedRecord.roleName,
                    description: selectedRecord.description,
                    userCount: selectedRecord.userCount,
                    addTime: moment(selectedRecord.addTime),
                    isEnabled: selectedRecord.isEnabled,
                } : {
                    roleName: '',
                    description: '',
                    userCount: 0,
                    addTime: moment(),
                    isEnabled: true,
                }}>
                    <Item name="roleName" label="角色名称" rules={[{ required: true, message: '请输入角色名称' }]}>
                        <Input />
                    </Item>
                    <Item name="description" label="描述" rules={[{ required: true, message: '请输入描述' }]}>
                        <Input />
                    </Item>
                    <Item name="userCount" label="用户数" rules={[{ required: true, message: '请输入用户数' }]}>
                        <InputNumber min={0} />
                    </Item>
                    <Item name="addTime" label="添加时间" rules={[{ required: true, message: '请选择添加时间' }]}>
                        <DatePicker />
                    </Item>
                    <Item name="isEnabled" label="是否启用" valuePropName="checked">
                        <Switch />
                    </Item>
                    <Item>
                        <Button type="primary" htmlType="submit">
                            {isAddMode ? '新增' : '保存'}
                        </Button>
                    </Item>
                </Form>
            </Modal>
            <Modal
                title="分配菜单"
                open={isMenuModalVisible}
                onOk={handleMenuOk}
                onCancel={handleMenuCancel}
            >
                <TreeSelect
                    treeData={menuData&&menuData.map(item => ({
                        ...item,
                        icon: item.icon ? IconMap[item.icon] : undefined // Safely access the 'icon' property
                    }))}
                    value={assignedMenus}
                    onChange={onChange}
                    treeCheckable={true}
                    showCheckedStrategy={SHOW_PARENT}
                    placeholder="Please select"
                    style={{ width: '100%' }}
                />
            </Modal>

        </>
    );
};

export default RoleTable;
